package com.senseuni.da.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.senseuni.da.R;
import com.senseuni.da.model.MediaItem;

import java.util.ArrayList;
import java.util.List;

public class MainContentAdapter extends RecyclerView.Adapter<MainContentAdapter.MyViewHolder> {

    private final Context mContext;
    private List<MediaItem> mDataList;

    public MainContentAdapter(Context context, List<MediaItem> list) {
        this.mContext = context;
        if (list == null) {
            mDataList = new ArrayList<>();
        } else {
            mDataList = list;
        }
    }

    public void setDataList(List<MediaItem> list) {
        mDataList = list;
    }

    public void addItem(MediaItem item) {
        mDataList.add(item);
        notifyItemInserted(mDataList.size() - 1);
    }

    public void insertItem(int position, MediaItem item) {
        if (position >= mDataList.size()) {
            mDataList.add(item);
            notifyItemInserted(mDataList.size() - 1);
        } else {
            mDataList.add(position, item);
            notifyItemInserted(position);
        }
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(mContext, R.layout.item_content_image, null);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(layoutParams);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MediaItem item = mDataList.get(position);
        if (item.type == 0) {
            Glide.with(mContext).load(item.resId).into(holder.mContentView);
        } else if (item.type == 1) {
            Glide.with(mContext).load(item.path).into(holder.mContentView);
        } else {
            Glide.with(mContext).load(item.url).into(holder.mContentView);
        }
    }

    @Override
    public int getItemCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView mContentView;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            mContentView = itemView.findViewById(R.id.imageView);
        }
    }
}
